#include "../head/cmd_parse.h"

int cmd_parse(const char *str, train_t *train, char **localAddr){
    char *copy = strdup(str);
    if(!copy) return -1;
    //处理换行符
    ssize_t length = strcspn(copy, "\n\r");
    copy[length] = '\0';
    //查找空格
    char *space = strchr(copy, ' ');
    char *str_cmd = copy;
    char *args = NULL;
    if(space){
        *space = '\0';
        args = space + 1;
    }
    //printf("str_cmd:%s.\n",str_cmd);
    //char *token = strtok(str_cmd, " ");    //首次调用strtok
    if(strncmp(str_cmd, "cd", 2) == 0){
        train->cmd = 0;
    }else if(strncmp(str_cmd, "ls", 2) == 0){
        train->cmd = 1;
    }else if(strncmp(str_cmd, "pwd", 3) == 0){
        train->cmd = 2;
    }else if(strncmp(str_cmd, "mkdir", 5) == 0){
        train->cmd = 3;
    }else if(strncmp(str_cmd, "rmdir", 5) == 0){
        train->cmd = 4;
    }else if(strncmp(str_cmd, "puts", 4) == 0){
        train->cmd = 5;
        //printf("ARGCbefore%s.\n", args);
        char *tmp = strchr(args, ' ');
        *tmp = '\0';
        char *addr_B = tmp + 1;
        char *addr_A = strtok(args, " ");
        //printf("ARGS:%s.\n", args);
        char cwd[128] = {0};
        if(addr_A[0] != '/'){   //如果用户输入是相对地址
            getcwd(cwd, sizeof(cwd));
            addr_A = strcat(cwd, addr_A);
        }
        if(access(addr_A, F_OK) == 0){  //判断本地文件路径是否合法
            //printf("ADDRB%s.\n", addr_B);
            *localAddr = strdup(addr_A);
            printf("localAddr:%s.\n",*localAddr);
            args = addr_B;
        }else{
            printf("Wrong Local FilePath, Please check again.\n");
            return 0;
        }
    }else if(strncmp(str_cmd, "gets", 4) == 0){
        train->cmd = 6;
        //printf("ARGCbefore%s.\n", args);
        char *tmp = strchr(args, ' ');
        *tmp = '\0';
        char *addr_B = tmp + 1;
        char *addr_A = strtok(args, " ");
        //printf("ARGS:%s.\n", args);
        char cwd[128] = {0};
        if(addr_A[0] != '/'){   //如果用户输入是相对地址
            getcwd(cwd, sizeof(cwd));
            addr_A = strcat(cwd, addr_A);
            //printf("addr_A = %s.\n", addr_A);
        }
        if(access(addr_A, F_OK) == 0){  //判断本地文件路径是否合法
            //printf("ADDRB%s.\n", addr_B);

            *localAddr = strdup(addr_A);
            //printf("localAddr:%s.\n",*localAddr);
            args = addr_B;
        }else{
            printf("Wrong Local FilePath, Please check again.\n");
            return 0;
        }
    }else if(strncmp(str_cmd, "remove", 6) == 0){
        train->cmd = 7;
    }else {
        //printf("Wrong cmd.\n");
        //do nothing
        free(copy);
        return -1;
    }
    if(args != NULL){
        //printf("args = %s\n", args);
        strncpy(train->data, args, sizeof(train->data) - 1);
        train->data[sizeof(train->data) - 1] = '\0';
        train->length = strlen(train->data);

    }else{
        train->data[0] = '\0';
    }
    free(copy);
    //printf("%d\n", train->cmd);
    return 0;
}
